package start.rabbitmq;

import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
@RabbitListener(queues = "TestTopicQueue")//监听的队列名称 TestTopicQueue
public class RabbitConsumer01 {

    @RabbitHandler
    @SneakyThrows
    public void process(Map testMessage, Message message, Channel channel) {
        try {
            Thread.sleep(1*100);
            log.info("TopicReceiver消费者收到Map消息  : " + testMessage.toString());
            Integer index = (Integer) testMessage.get("index");
            if(index.equals(10)) {
                throw new RuntimeException("异常阻断");
            }
            //消费成功，确认消息
            //channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {Integer retryCount = (Integer) message.getMessageProperties().getHeaders().get("retryCount");
            if (retryCount == null) {
                retryCount = 0;
            }
            log.info("当前重试次数" + retryCount);
            if(retryCount < 10) {
                Thread.sleep(2*1000);
                message.getMessageProperties().getHeaders().put("retryCount",  ++retryCount);
                throw new RuntimeException("强制异常");
            }
            log.info(e.getMessage());
            //消费成功，确认消息
            //nack返回false，并重新回到队列
            //channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            //channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }

    @RabbitHandler
    @SneakyThrows
    public void process(String testMessage) {
        Thread.sleep(1*100);
        log.info("TopicReceiver消费者收到String消息  : " + testMessage.toString());
    }

    @RabbitHandler
    @SneakyThrows
    public void process(Integer testMessage) {
        Thread.sleep(1*100);
        log.info("TopicReceiver消费者收到Integer消息  : " + testMessage.toString());
    }

}